//
//  JTPictureSelectionView.m
//

#import "JTPictureSelectionView.h"

@interface JTPictureSelectionView ()


@end

@implementation JTPictureSelectionView

-(instancetype)initWithFrame:(CGRect)frame
{
    if (self=[super initWithFrame:frame]) {
        self.config=[JTPictureSelectionViewConfiguration defaultConfiguration];
        self.pictures=[[NSMutableArray alloc] init];
        self.userInteractionEnabled=YES;
    }
    return self;
}

-(void)addPicture:(UIImage*)picture
{
    NSInteger tag=self.pictures.count;
    [self.pictures addObject:picture];
    NSUInteger index=self.subviews.count;
    NSUInteger column=index%3;
    NSUInteger row=index/3;
    UIImageView* pictureView=[[UIImageView alloc] initWithImage:picture];
    pictureView.tag=tag;
    CGFloat width=(self.bounds.size.width-self.config.margin*2-self.config.gap*(self.config.numberOfColumns-1))/3;
    CGFloat height=width*11.0/17.0;
    pictureView.frame=CGRectMake(self.config.margin+(width+self.config.gap)*column, (height+self.config.gap)*row, width, height);
    [self addSubview:pictureView];
    
    UIButton* deleteButton=[UIButton buttonWithType:UIButtonTypeCustom];
    [deleteButton setBackgroundImage:[UIImage imageNamed:@"delete-button"] forState:UIControlStateNormal];
    deleteButton.frame=CGRectMake(0, 0, 16, 16);
    deleteButton.center=CGPointMake(width-5, 5);
    deleteButton.tag=tag;
    [deleteButton addTarget:self action:@selector(deleteButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [pictureView addSubview:deleteButton];
    pictureView.userInteractionEnabled=YES;
}

-(void)deleteButtonPressed:(UIButton*)sender
{
    [self removePictureAtIndex:sender.tag];
}

-(void)addPictures:(NSArray *)pictures
{
    for (UIImage* picture in pictures) {
        [self addPicture:picture];
    }
}

-(void)removePictureAtIndex:(NSUInteger)index
{
    if (index<self.pictures.count) {
        [self.pictures removeObjectAtIndex:index];
        for (UIView* view in self.subviews) {
            if (view.tag==index) {
                [view removeFromSuperview];
            }else if (view.tag>index){
                view.tag-=1;
                ((UIView*)view.subviews.firstObject).tag-=1;
                NSUInteger column=view.tag%3;
                NSUInteger row=view.tag/3;
                CGFloat width=(self.bounds.size.width-self.config.margin*2-self.config.gap*(self.config.numberOfColumns-1))/3;
                CGFloat height=width*11.0/17.0;
                [UIView animateWithDuration:0.4 animations:^{
                    view.frame=CGRectMake(self.config.margin+(width+self.config.gap)*column, (height+self.config.gap)*row, width, height);
                }];
            }
        }
    }
}

@end
